import React from 'react'
import { Card, Avatar, Space, Tag, Button, Spin } from 'antd'
import { UserOutlined, EditOutlined, CrownOutlined } from '@ant-design/icons'
import { useUserStore } from '@/stores'
import { useNavigate } from 'react-router-dom'

const UserInfoCard: React.FC = () => {
  const { user, isLoading } = useUserStore()
  const navigate = useNavigate()

  const getAvatar = () => {
    if (user?.avatar) {
      return <Avatar size={80} src={user.avatar} />
    }
    const firstLetter = (user?.username || user?.email || 'U')[0].toUpperCase()
    return (
      <Avatar 
        size={80} 
        style={{ backgroundColor: '#87d068', fontSize: '32px' }}
      >
        {firstLetter}
      </Avatar>
    )
  }

  const getMemberLevel = () => {
    if (user?.role === 'admin') {
      return (
        <Tag color="gold" icon={<CrownOutlined />}>
          管理员
        </Tag>
      )
    }
    return (
      <Tag color="blue" icon={<UserOutlined />}>
        普通用户
      </Tag>
    )
  }

  if (isLoading) {
    return (
      <Card className="text-center">
        <Spin tip="加载中..." />
      </Card>
    )
  }

  if (!user) {
    return (
      <Card className="text-center">
        <p>请先登录</p>
      </Card>
    )
  }

  return (
    <Card 
      className="hover:shadow-lg transition-shadow duration-300"
      title="用户信息"
      extra={
        <Button 
          type="text" 
          icon={<EditOutlined />}
          onClick={() => navigate('/profile')}
        >
          编辑资料
        </Button>
      }
    >
      <div className="flex flex-col items-center text-center">
        {getAvatar()}
        
        <Space direction="vertical" size="small" className="mt-4">
          <h3 className="text-lg font-semibold m-0">
            {user.username || user.email}
          </h3>
          
          <p className="text-gray-500 m-0">
            {user.email}
          </p>
          
          <div className="mt-2">
            {getMemberLevel()}
          </div>
          
          <div className="mt-4 text-sm text-gray-400">
            注册时间: {new Date(user.createdAt).toLocaleDateString('zh-CN')}
          </div>
        </Space>
      </div>
    </Card>
  )
}

export default React.memo(UserInfoCard)

export { UserInfoCard }